import os
import datetime
from flask import Flask, request, session, redirect, jsonify
from flask_cors import CORS
from flask import render_template
from src.config.dbconfig import DbConfig
from src.db.flaskdb import db
from src.router.router import register_router
from src.service.loginservice import login_check
from src.util.configutil import get_server_config
import jwt

# 创建flask应用
app = Flask(__name__, static_folder="static", template_folder="templates")
SECRET_KEY = os.urandom(24)
app.secret_key = os.urandom(24)
# 允许跨域cors访问
CORS(app=app)
# 允许跨域cors访问. 
CORS(app=app)
# 配置数据库
app.config.from_object(DbConfig)
# 数据库初始化
db.init_app(app)
# 注册路由
register_router(app=app)
# 获取服务器配置信息
server_config = get_server_config()


# 注册定时任务并启动
# register_job_and_start(app)

# 用于生成和验证JWT的函数
def create_jwt(user_id, expire=3600):
    payload = {
        'iat': datetime.datetime.utcnow(),
        'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=expire),
        'sub': user_id
    }
    token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
    return token


def verify_jwt(token):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
        print(payload)
        return payload['sub']
    except jwt.ExpiredSignatureError:
        return False
    except jwt.InvalidTokenError:
        return False


# @app.before_request
# def before_request():
#     request_path = request.path
#     if request_path != "/login" and not request_path.startswith("/static"):
#         # 如果是请求的登录页面
#         username = session.get("username")
#         if username is None:
#             return redirect("/login")
#     elif request_path == "/login":
#         username = session.get("username")
#         if username is not None:
#             return redirect("/")


@app.route("/")
def index():
    # return "api is running..."
    # return render_template('upload.html')
    # return redirect(url_for("predict_app.get_org_manager"))
    return render_template("index.html")


@app.route("/login", methods=["GET", "POST"])
def login_page():
    if request.method.lower() == "get":
        return render_template("login1.html")
    else:
        uname = request.form.get("uname")
        upwd = request.form.get("pwd")
        login_res = login_check(uname, upwd)
        if login_res.get("code") == 200:
            token = create_jwt(user_id=uname)
            print(token)
            return jsonify({'token': token, 'code': 200, 'msg': '登录成功'})
        return login_res
        # return login_check(uname, upwd)


def main():
    app.run(host=server_config.get("host"), port=server_config.get("port"), debug=server_config.get("debug"))


if __name__ == "__main__":
    main()
